#!/usr/bin/env python
#coding: utf-8

"""
缓存序列换操作方法
"""

import os
import sys

from lib.core.log import logger as log

#序列化一个字典
def serialize(dic):
    result = False
    filename = "mm_crawler.cache"
    filepath = "./logs/"
    if not os.path.exists(filepath):
        os.mkdir(filepath)
    str = ""
    output  = None
    filename = "%s%s" % (filepath, filename)
    if isinstance(dic,dict):
        for k in dic:
            str += "%s=%s\n" % (k, dic[k])
        try:  
            output = open(filename, 'w')    
            output.write(str)
            result = True
            log.info("serialize file success! [%s]" % (filename))
        finally:  
            output.close()
    return result
 
#根据一个文件名名称反序列化一个字典
def deserialize():
    filename = "./logs/mm_crawler.cache"
    result = {}
    if os.path.exists(filename):    
        try:  
            output = open(filename, 'r') 
            while True: 
                line = output.readline()
                if line:
                    #print line.decode("utf-8")
                    col = line.split('=')
                    result[col[0]] = col[1].decode("utf-8")
                else:
                    break
        finally:  
            output.close()
    return result